package com.uniflow.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uniflow.common.PageResult;
import com.uniflow.common.Result;
import com.uniflow.common.ResultCode;
import com.uniflow.entity.AuditLogs;
import com.uniflow.service.AuditLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审计日志管理控制器
 * 
 * @author uniflow
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/v1/audit-logs")
@Validated
@Api(tags = "审计日志管理")
public class AuditLogController {
    
    @Autowired
    private AuditLogService auditLogService;
    
    /**
     * 分页查询审计日志列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("分页查询审计日志列表")
    public Result<PageResult<AuditLogs>> getAuditLogList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("用户ID") @RequestParam(required = false) String userId,
            @ApiParam("用户名") @RequestParam(required = false) String username,
            @ApiParam("操作类型") @RequestParam(required = false) String operationType,
            @ApiParam("资源类型") @RequestParam(required = false) String resourceType,
            @ApiParam("资源ID") @RequestParam(required = false) String resourceId,
            @ApiParam("操作结果") @RequestParam(required = false) String operationResult,
            @ApiParam("请求IP") @RequestParam(required = false) String requestIp,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("关键词") @RequestParam(required = false) String keyword) {
        try {
            IPage<AuditLogs> page = auditLogService.getAuditLogPage(pageNum, pageSize, userId, username,
                    operationType, resourceType, resourceId, operationResult, requestIp, startDate, endDate, keyword);
            PageResult<AuditLogs> result = new PageResult<AuditLogs>(pageNum, pageSize, page.getTotal(), page.getRecords());
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 根据ID查询审计日志详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("根据ID查询审计日志详情")
    public Result<AuditLogs> getAuditLogById(@ApiParam("日志ID") @PathVariable String id) {
        try {
            AuditLogs auditLog = auditLogService.getAuditLogWithDetails(id);
            if (auditLog == null) {
                return Result.error(ResultCode.NOT_FOUND, "审计日志不存在");
            }
            return Result.success(auditLog);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询审计日志
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("根据用户ID查询审计日志")
    public Result<List<AuditLogs>> getAuditLogsByUserId(
            @ApiParam("用户ID") @PathVariable String userId,
            @ApiParam("限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AuditLogs> logs = auditLogService.getAuditLogsByUserId(userId, limit);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 根据操作类型查询审计日志
     */
    @GetMapping("/operation-type/{operationType}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("根据操作类型查询审计日志")
    public Result<List<AuditLogs>> getAuditLogsByOperationType(
            @ApiParam("操作类型") @PathVariable String operationType,
            @ApiParam("限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AuditLogs> logs = auditLogService.getAuditLogsByOperationType(operationType, limit);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 根据资源类型查询审计日志
     */
    @GetMapping("/resource-type/{resourceType}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("根据资源类型查询审计日志")
    public Result<List<AuditLogs>> getAuditLogsByResourceType(
            @ApiParam("资源类型") @PathVariable String resourceType,
            @ApiParam("限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AuditLogs> logs = auditLogService.getAuditLogsByResourceType(resourceType, limit);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 根据资源ID查询审计日志
     */
    @GetMapping("/resource/{resourceType}/{resourceId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("根据资源ID查询审计日志")
    public Result<List<AuditLogs>> getAuditLogsByResourceId(
            @ApiParam("资源类型") @PathVariable String resourceType,
            @ApiParam("资源ID") @PathVariable String resourceId) {
        try {
            List<AuditLogs> logs = auditLogService.getAuditLogsByResourceId(resourceType, resourceId);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 根据IP地址查询审计日志
     */
    @GetMapping("/ip/{requestIp}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("根据IP地址查询审计日志")
    public Result<List<AuditLogs>> getAuditLogsByRequestIp(
            @ApiParam("请求IP") @PathVariable String requestIp,
            @ApiParam("限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AuditLogs> logs = auditLogService.getAuditLogsByRequestIp(requestIp, limit);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询指定时间范围内的审计日志
     */
    @GetMapping("/date-range")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询指定时间范围内的审计日志")
    public Result<List<AuditLogs>> getAuditLogsByDateRange(
            @ApiParam("开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<AuditLogs> logs = auditLogService.getAuditLogsByDateRange(startDate, endDate);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询今日审计日志统计
     */
    @GetMapping("/stats/today")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询今日审计日志统计")
    public Result<Map<String, Object>> getTodayStats() {
        try {
            Map<String, Object> stats = auditLogService.getTodayStats();
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询审计日志统计信息
     */
    @GetMapping("/stats")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询审计日志统计信息")
    public Result<Map<String, Object>> getAuditStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            Map<String, Object> stats = auditLogService.getAuditStats(startDate, endDate);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询操作类型统计
     */
    @GetMapping("/stats/operation-type")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询操作类型统计")
    public Result<List<Map<String, Object>>> getOperationTypeStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<Map<String, Object>> stats = auditLogService.getOperationTypeStats(startDate, endDate);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询资源类型统计
     */
    @GetMapping("/stats/resource-type")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询资源类型统计")
    public Result<List<Map<String, Object>>> getResourceTypeStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<Map<String, Object>> stats = auditLogService.getResourceTypeStats(startDate, endDate);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询用户操作统计
     */
    @GetMapping("/stats/user-operation")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询用户操作统计")
    public Result<List<Map<String, Object>>> getUserOperationStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Map<String, Object>> stats = auditLogService.getUserOperationStats(startDate, endDate, limit);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询操作结果统计
     */
    @GetMapping("/stats/operation-result")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询操作结果统计")
    public Result<List<Map<String, Object>>> getOperationResultStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<Map<String, Object>> stats = auditLogService.getOperationResultStats(startDate, endDate);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询IP访问统计
     */
    @GetMapping("/stats/ip-access")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询IP访问统计")
    public Result<List<Map<String, Object>>> getIpAccessStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Map<String, Object>> stats = auditLogService.getIpAccessStats(startDate, endDate, limit);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询时段访问统计
     */
    @GetMapping("/stats/hourly-access")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询时段访问统计")
    public Result<List<Map<String, Object>>> getHourlyAccessStats(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<Map<String, Object>> stats = auditLogService.getHourlyAccessStats(startDate, endDate);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询失败操作统计
     */
    @GetMapping("/failed-operations")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询失败操作统计")
    public Result<List<AuditLogs>> getFailedOperations(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AuditLogs> logs = auditLogService.getFailedOperations(startDate, endDate, limit);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询高风险操作
     */
    @GetMapping("/high-risk-operations")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询高风险操作")
    public Result<List<AuditLogs>> getHighRiskOperations(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AuditLogs> logs = auditLogService.getHighRiskOperations(startDate, endDate, limit);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询异常IP访问
     */
    @GetMapping("/abnormal-ip-access")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询异常IP访问")
    public Result<List<Map<String, Object>>> getAbnormalIpAccess(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<Map<String, Object>> abnormal = auditLogService.getAbnormalIpAccess(startDate, endDate);
            return Result.success(abnormal);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询频繁操作用户
     */
    @GetMapping("/frequent-users")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询频繁操作用户")
    public Result<List<Map<String, Object>>> getFrequentUsers(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Map<String, Object>> users = auditLogService.getFrequentUsers(startDate, endDate, limit);
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询资源访问热度
     */
    @GetMapping("/resource-access-heat/{resourceType}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询资源访问热度")
    public Result<List<Map<String, Object>>> getResourceAccessHeat(
            @ApiParam("资源类型") @PathVariable String resourceType,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<Map<String, Object>> heat = auditLogService.getResourceAccessHeat(resourceType, startDate, endDate, limit);
            return Result.success(heat);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询操作趋势
     */
    @GetMapping("/operation-trend")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询操作趋势")
    public Result<List<Map<String, Object>>> getOperationTrend(
            @ApiParam("操作类型") @RequestParam(required = false) String operationType,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("分组方式") @RequestParam(defaultValue = "day") String groupBy) {
        try {
            List<Map<String, Object>> trend = auditLogService.getOperationTrend(operationType, startDate, endDate, groupBy);
            return Result.success(trend);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询安全事件
     */
    @GetMapping("/security-events")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询安全事件")
    public Result<List<AuditLogs>> getSecurityEvents(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<AuditLogs> events = auditLogService.getSecurityEvents(startDate, endDate);
            return Result.success(events);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询数据变更记录
     */
    @GetMapping("/data-changes/{resourceType}/{resourceId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询数据变更记录")
    public Result<List<AuditLogs>> getDataChanges(
            @ApiParam("资源类型") @PathVariable String resourceType,
            @ApiParam("资源ID") @PathVariable String resourceId) {
        try {
            List<AuditLogs> changes = auditLogService.getDataChanges(resourceType, resourceId);
            return Result.success(changes);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询用户登录记录
     */
    @GetMapping("/user-login/{userId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询用户登录记录")
    public Result<List<AuditLogs>> getUserLoginLogs(
            @ApiParam("用户ID") @PathVariable String userId,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<AuditLogs> logs = auditLogService.getUserLoginLogs(userId, startDate, endDate);
            return Result.success(logs);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询权限变更记录
     */
    @GetMapping("/permission-changes/{userId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询权限变更记录")
    public Result<List<AuditLogs>> getPermissionChanges(
            @ApiParam("用户ID") @PathVariable String userId,
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<AuditLogs> changes = auditLogService.getPermissionChanges(userId, startDate, endDate);
            return Result.success(changes);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询系统配置变更记录
     */
    @GetMapping("/config-changes")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询系统配置变更记录")
    public Result<List<AuditLogs>> getConfigChanges(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            List<AuditLogs> changes = auditLogService.getConfigChanges(startDate, endDate);
            return Result.success(changes);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询审计日志链路
     */
    @GetMapping("/chain/{traceId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询审计日志链路")
    public Result<List<AuditLogs>> getLogChain(@ApiParam("追踪ID") @PathVariable String traceId) {
        try {
            List<AuditLogs> chain = auditLogService.getLogChain(traceId);
            return Result.success(chain);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询相关审计日志
     */
    @GetMapping("/related/{resourceType}/{resourceId}")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询相关审计日志")
    public Result<List<AuditLogs>> getRelatedLogs(
            @ApiParam("资源类型") @PathVariable String resourceType,
            @ApiParam("资源ID") @PathVariable String resourceId,
            @ApiParam("操作时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime operationTime,
            @ApiParam("时间范围(分钟)") @RequestParam(defaultValue = "30") Integer timeRange) {
        try {
            List<AuditLogs> related = auditLogService.getRelatedLogs(resourceType, resourceId, operationTime, timeRange);
            return Result.success(related);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询合规性报告数据
     */
    @GetMapping("/compliance-report")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询合规性报告数据")
    public Result<List<Map<String, Object>>> getComplianceReportData(
            @ApiParam("开始时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate,
            @ApiParam("报告类型") @RequestParam(defaultValue = "general") String reportType) {
        try {
            List<Map<String, Object>> report = auditLogService.getComplianceReportData(startDate, endDate, reportType);
            return Result.success(report);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 清理过期审计日志
     */
    @DeleteMapping("/cleanup")
    @PreAuthorize("hasAuthority('audit:write')")
    @ApiOperation("清理过期审计日志")
    public Result<Map<String, Object>> cleanupExpiredLogs(
            @ApiParam("过期时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime expireDate) {
        try {
            int deletedCount = auditLogService.cleanupExpiredLogs(expireDate);
            Map<String, Object> result = new HashMap<>();
            result.put("deletedCount", deletedCount);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 归档审计日志
     */
    @PostMapping("/archive")
    @PreAuthorize("hasAuthority('audit:write')")
    @ApiOperation("归档审计日志")
    public Result<Map<String, Object>> archiveLogs(
            @ApiParam("归档时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime archiveDate) {
        try {
            int archivedCount = auditLogService.archiveLogs(archiveDate);
            Map<String, Object> result = new HashMap<>();
            result.put("archivedCount", archivedCount);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询审计日志总数
     */
    @GetMapping("/count/total")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询审计日志总数")
    public Result<Long> getTotalCount() {
        try {
            Long count = auditLogService.getTotalCount();
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询指定时间范围内的日志数量
     */
    @GetMapping("/count/date-range")
    @PreAuthorize("hasAuthority('audit:read')")
    @ApiOperation("查询指定时间范围内的日志数量")
    public Result<Long> getCountByDateRange(
            @ApiParam("开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @ApiParam("结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        try {
            Long count = auditLogService.getCountByDateRange(startDate, endDate);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(ResultCode.ERROR, e.getMessage());
        }
    }
}